"""
SimpleOrm 功能测试脚本

快速测试 SimpleOrm 的各项功能是否正常工作。
"""

import asyncio
from tortoise.models import Model
from tortoise import fields
from simpleapi import simple_orm


class TestUser(Model):
    id = fields.IntField(pk=True)
    username = fields.CharField(max_length=50, unique=True)
    email = fields.CharField(max_length=100)
    age = fields.IntField(null=True)
    
    class Meta:
        table = "test_users"


async def test_simple_orm():
    """测试 SimpleOrm 的各项功能"""
    print("🧪 开始测试 SimpleOrm 功能...")
    
    try:
        # 1. 测试自动发现和初始化
        print("\n1️⃣ 测试自动发现和初始化")
        await simple_orm.init(
            db_url="sqlite://test.db",
            generate_schemas=True
        )
        print("✅ 自动发现和初始化成功")
        
        # 2. 测试清空表
        print("\n2️⃣ 测试清空表")
        await simple_orm.truncate_table(TestUser)
        print("✅ 清空表成功")
        
        # 3. 测试创建
        print("\n3️⃣ 测试创建用户")
        user1 = await simple_orm.create(TestUser, username="test1", email="test1@example.com", age=25)
        user2 = await simple_orm.create(TestUser, username="test2", email="test2@example.com", age=30)
        print(f"✅ 创建用户成功: {user1}, {user2}")
        
        # 4. 测试获取
        print("\n4️⃣ 测试获取用户")
        found_user = await simple_orm.get(TestUser, username="test1")
        print(f"✅ 获取用户成功: {found_user}")
        
        # 5. 测试列表查询
        print("\n5️⃣ 测试列表查询")
        users = await simple_orm.list(TestUser, limit=10, order_by=["username"])
        print(f"✅ 列表查询成功: {len(users)} 个用户")
        
        # 6. 测试统计
        print("\n6️⃣ 测试统计功能")
        count = await simple_orm.count(TestUser)
        exists = await simple_orm.exists(TestUser, username="test1")
        print(f"✅ 统计功能成功: 总数={count}, test1存在={exists}")
        
        # 7. 测试查询构建器
        print("\n7️⃣ 测试查询构建器")
        adult_users = await (simple_orm.query(TestUser)
                           .filter(age__gte=18)
                           .order_by("-age")
                           .all())
        print(f"✅ 查询构建器成功: {len(adult_users)} 个成年用户")
        
        # 8. 测试更新
        print("\n8️⃣ 测试更新功能")
        updated_count = await simple_orm.update(
            TestUser,
            filter_kwargs={"username": "test1"},
            age=26
        )
        print(f"✅ 更新功能成功: 更新了 {updated_count} 条记录")
        
        # 9. 测试批量创建
        print("\n9️⃣ 测试批量创建")
        batch_data = [
            {"username": f"batch{i}", "email": f"batch{i}@example.com", "age": 20 + i}
            for i in range(1, 4)
        ]
        batch_users = await simple_orm.bulk_create(TestUser, batch_data)
        print(f"✅ 批量创建成功: {len(batch_users)} 个用户")
        
        # 10. 测试数据序列化
        print("\n🔟 测试数据序列化")
        try:
            # 重新获取用户确保数据完整
            test_user = await simple_orm.get(TestUser, username="test1")
            user_dict = simple_orm.to_dict(test_user)
            users_dict_list = simple_orm.to_dict_list(users[:2], include=["id", "username"])
            print(f"✅ 数据序列化成功: 单个={len(user_dict)}字段, 列表={len(users_dict_list)}项")
        except Exception as e:
            print(f"❌ 数据序列化失败: {e}")
            import traceback
            traceback.print_exc()
        
        # 11. 测试表信息
        print("\n1️⃣1️⃣ 测试表信息")
        table_info = await simple_orm.get_table_info(TestUser)
        print(f"✅ 表信息获取成功: {table_info['table_name']}, {len(table_info['fields'])}个字段")
        
        # 12. 测试 get_or_create
        print("\n1️⃣2️⃣ 测试 get_or_create")
        user, created = await simple_orm.get_or_create(
            TestUser,
            defaults={"email": "new@example.com", "age": 35},
            username="new_user"
        )
        print(f"✅ get_or_create 成功: 用户={user.username}, 新创建={created}")
        
        # 13. 最终统计
        print("\n📊 最终统计")
        final_count = await simple_orm.count(TestUser)
        print(f"✅ 最终用户总数: {final_count}")
        
        print("\n🎉 所有测试通过！SimpleOrm 功能正常！")
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        await simple_orm.close()
        print("✅ 数据库连接已关闭")
    
    return True


if __name__ == "__main__":
    success = asyncio.run(test_simple_orm())
    if success:
        print("\n🏆 SimpleOrm 测试完成，所有功能正常！")
    else:
        print("\n💥 SimpleOrm 测试失败，请检查错误信息！") 